import {getUserTempId} from '@/utils/userAbout'
import {registerUser,sendCode,loginUser,getUserInfo} from '@/ajax'
const state = {
  userTempId: getUserTempId(),
  token: localStorage.getItem('TOKEN_KEY'),
  userInfo: {

  }
}
const actions = {
  //定义注册用户action
  async registerUser({commit},userObj) {
    let result = await registerUser(userObj)
    if(result.code === 200) {
      return 'ok'
    }else {
      return Promise.reject(new Error('注册用户失败'))
    }
  },
  //定义发送验证码action
  async sendCode({commit},phone) {
    let result = await sendCode(phone)
    if(result.code === 200) {
      return result.data
    }else {
      return Promise.reject(new Error('验证码发送失败'))
    }
  },
  //定义用户登录action
  async loginUser({commit,dispatch},{phone,password}) {
    let result = await loginUser({phone,password})
    if(result.code === 200) {
      commit('SAVE_TOKEN',result.data.token)
      localStorage.setItem('TOKEN_KEY',result.data.token)
      return 'ok'
    }else {
      return Promise.reject(new Error('用户登录失败'))
    }
  },
  //定义得到用户信息
  async getUserInfo({commit}) {
    let result = await getUserInfo()
    if(result.code === 200) {
      commit('GETUSERINFO',result.data)
      return 'ok'
    }else {
      return Promise.reject(new Error('获取用户信息失败'))
    }
  },
  //清楚Token
  clearToken({commit}) {
    localStorage.removeItem('TOKEN_KEY')
    commit('CLEAR_TOKEN')
  }
}
const mutations = {
  SAVE_TOKEN(state,token) {
    state.token = token
  },
  GETUSERINFO(state,userInfo) {
    state.userInfo = userInfo
  },
  CLEAR_TOKEN(state) {
    state.token = '',
    state.userInfo = {}
  }
}
const getters = {
  
}
export default {
  state,
  actions,
  mutations,
  getters
}